package com.lineage.server.timecontroller.pet;

import com.lineage.server.datatables.ItemTable;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DollGetTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(DollGetTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
  
  public void run() {
    try {
      Collection all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        if (tgpc.get_doll_get_time_src() > 0 && checkErr(tgpc)) {
          int itemid = tgpc.get_doll_get()[0];
          int count = tgpc.get_doll_get()[1];
          L1ItemInstance item = ItemTable.get().createItem(itemid);
          if (item != null) {
            item.setCount(count);
            if (tgpc.getInventory().checkAddItem(item, count) == 0) {
              tgpc.getInventory().storeItem(item);
              tgpc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item.getLogName()));
            } 
          } 
          Thread.sleep(50L);
        } 
      } 
    } catch (Exception e) {
      _log.error("魔法娃娃处理时间轴(赠送道具)异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      DollGetTimer dollTimer = new DollGetTimer();
      dollTimer.start();
    } 
  }
  
  private static boolean checkErr(L1PcInstance tgpc) {
    try {
      if (tgpc == null)
        return false; 
      if (tgpc.getOnlineStatus() == 0)
        return false; 
      if (tgpc.getNetConnection() == null)
        return false; 
      if (tgpc.isTeleport())
        return false; 
      int newtime = tgpc.get_doll_get_time() - 1;
      tgpc.set_doll_get_time(newtime);
      if (newtime <= 0) {
        tgpc.set_doll_get_time(tgpc.get_doll_get_time_src());
        return true;
      } 
    } catch (Exception e) {
      return false;
    } 
    return false;
  }
}
